<template>
  <!-- 会员信息详情页面 - 订单信息组件 -->
  <div>
    <!-- 搜索框 -->
    <el-form ref="table_form" :model="table_form" class="table-search-noshadow" :inline="true" label-width="100px">
      <el-form-item label="课程：" prop="courseId">
        <el-select clearable v-model="table_form.courseId" placeholder="请选择课程！">
          <el-option
            v-for="item in course_data"
            :key="item.courseManagementId"
            :label="item.courseName"
            :value="item.courseManagementId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="门店：" prop="buyCourseStoreId">
        <el-select clearable v-model="table_form.buyCourseStoreId" placeholder="请选择门店！" @change="handle_store">
          <el-option
            v-for="item in store_data"
            :key="item.id"
            :label="item.storeName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="教练：" prop="saleUserId">
        <el-select clearable v-model="table_form.saleUserId" placeholder="请选择教练！">
          <el-option
            v-for="item in coach_data"
            :key="item.id"
            :label="item.realName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="订单号：" prop="orderNumber">
        <el-input v-model="table_form.orderNumber" placeholder="请输入订单号！"></el-input>
      </el-form-item>

      <el-form-item label="是否补录：" prop="additionalOrder">
        <el-select clearable v-model="table_form.additionalOrder" placeholder="请选择教练！">
          <el-option label="是" value="0"></el-option>
          <el-option label="否" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="付款方式：" prop="tariffManagementId">
        <el-select clearable v-model="table_form.tariffManagementId" placeholder="请选择付款方式！">
          <el-option
            v-for="item in pay_data"
            :key="item.id"
            :label="item.channelName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间：" prop="endTime">
        <el-date-picker 
          value-format="yyyy-MM-dd HH:mm:ss" 
          v-model="table_form.endTime" 
          type="daterange" 
          :unlink-panels="true"
          :default-time="['00:00:00', '23:59:59']"
          > </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handle_search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handle_reset">重置</el-button>
      </el-form-item>
    </el-form>

     <!-- 表格顶部的操作按钮 -->
    <div class="btn-box">
      <!-- 接口返回按钮 -->
      <div class="left">
        <el-button type="primary" v-for="item in btn_data" :key="item.buttonHtmlLayEvent" @click="handle_table_btn(item.buttonHtmlLayEvent)">{{ item.menuDetailButtonName }}</el-button>
      </div>
      <!-- 表格列显示、隐藏 -->
      <div class="right">
        <el-popover
          placement="bottom-end"
          width="130"
          trigger="click">

          <el-checkbox v-model="checked_obj.orderNumber">订单号</el-checkbox>
          <el-checkbox v-model="checked_obj.autoStatus">订单状态</el-checkbox>
          <el-checkbox v-model="checked_obj.storeName">门店名称</el-checkbox>
          <el-checkbox v-model="checked_obj.realName">销售人员名称</el-checkbox>
          <el-checkbox v-model="checked_obj.vipuser">会员/会员名字</el-checkbox>
          <el-checkbox v-model="checked_obj.phone">会员手机</el-checkbox>
          <el-checkbox v-model="checked_obj.courseManagement">课程名称</el-checkbox>
          <el-checkbox v-model="checked_obj.introduction">业务种类</el-checkbox>
          <el-checkbox v-model="checked_obj.purchaseQuantity">购课(节)/剩余(节)</el-checkbox>
          <el-checkbox v-model="checked_obj.unitPrice">课程单价/收入单价</el-checkbox>
          <el-checkbox v-model="checked_obj.earnestMoney">支付金额/收入金额</el-checkbox>
          <el-checkbox v-model="checked_obj.earnestMoney_price">定金金额</el-checkbox>
          <el-checkbox v-model="checked_obj.tariffManagement">支付渠道</el-checkbox>
          <el-checkbox v-model="checked_obj.termOfValidityEnd">有效期</el-checkbox>
          <el-checkbox v-model="checked_obj.contractUrl">合同是否上传</el-checkbox>
          <el-checkbox v-model="checked_obj.createTime">创建时间</el-checkbox>
          <el-checkbox v-model="checked_obj.createUser">创建人</el-checkbox>

          <el-button slot="reference" type="primary" icon="iconfont icon-faxianxuanze"></el-button>
        </el-popover>
        <!-- 导出excell -->
        <el-button type="primary" icon="iconfont icon-export" @click="handle_excell"></el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table id="excell-table" :data="tableData" border header-cell-class-name="table-style" @selection-change="handle_select">
      <el-table-column type="selection" width="55" align="center"></el-table-column>

      <el-table-column label="订单号" align="center" v-if="checked_obj.orderNumber">
        <template slot-scope="scope"> {{ scope.row.orderNumber || '--' }} </template>
      </el-table-column>

      <el-table-column label="订单状态" align="center" v-if="checked_obj.autoStatus">
        <template slot-scope="scope"> 
          <el-tag v-if="set_order_type(scope.row) == 1" type="info">已退课</el-tag>
          <el-tag v-if="set_order_type(scope.row) == 2" type="danger">即将过期</el-tag>
          <el-tag v-if="set_order_type(scope.row) == 3" type="info">已过期</el-tag>
          <el-tag v-if="set_order_type(scope.row) == 4" type="info">已过期/不正常订单</el-tag>
          <el-tag v-if="set_order_type(scope.row) == 5" type="warning">已完课</el-tag>
          <el-tag v-if="set_order_type(scope.row) == 6" type="success">正常</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="门店名称" align="center" v-if="checked_obj.storeName">
        <template slot-scope="scope"> {{ scope.row.enterpriseStore.storeName || '--' }} </template>
      </el-table-column>

      <el-table-column label="销售人员名称" align="center" v-if="checked_obj.realName">
        <template slot-scope="scope"> {{ scope.row.saleUser.realName || '--' }} </template>
      </el-table-column>

      <el-table-column label="会员/会员名字" align="center" v-if="checked_obj.vipuser">
        <template slot-scope="scope">{{ scope.row.vipUser.wxName }} / {{ scope.row.vipUser.realName }}</template>
      </el-table-column>

      <el-table-column label="会员手机" align="center" v-if="checked_obj.phone">
        <template slot-scope="scope"> {{ scope.row.vipUser.phone || '--' }} </template>
      </el-table-column>

      <el-table-column label="课程名称" align="center" v-if="checked_obj.courseManagement">
        <template slot-scope="scope"> {{ scope.row.courseManagement.title || '--' }} </template>
      </el-table-column>

      <el-table-column label="业务种类" align="center" v-if="checked_obj.introduction">
        <template slot-scope="scope">
          <span v-if="scope.row.introduction == 0">新单</span>
          <span v-if="scope.row.introduction == 1">转介绍</span>
          <span v-if="scope.row.introduction == 2">续单</span>
        </template>
      </el-table-column>

      <el-table-column label="购课(节)/剩余(节)" align="center" v-if="checked_obj.purchaseQuantity">
        <template slot-scope="scope">
          {{ scope.row.purchaseQuantity }} / {{ scope.row.remainingQuantity }}
        </template>
      </el-table-column>

      <el-table-column label="课程单价/收入单价" align="center" v-if="checked_obj.unitPrice">
        <template slot-scope="scope">
          {{ scope.row.unitPrice }} / {{ scope.row.revenueUnitPrice }}
        </template>
      </el-table-column>

      <el-table-column label="支付金额/收入金额" align="center" v-if="checked_obj.earnestMoney">
        <template slot-scope="scope">
          <span v-if="scope.row.earnestMoney">{{ scope.row.orderPrice - scope.row.earnestMoney.price }} / {{ scope.row.incomeAmount }}</span>
          <span v-else>{{ scope.row.orderPrice }} / {{ scope.row.incomeAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="定金金额" align="center" v-if="checked_obj.earnestMoney_price">
        <template slot-scope="scope">
          <span v-if="scope.row.earnestMoney">{{ scope.row.earnestMoney.price }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>

      <el-table-column label="支付渠道" align="center" v-if="checked_obj.tariffManagement">
        <template slot-scope="scope"> {{ scope.row.tariffManagement.channelName }} </template>
      </el-table-column>

      <el-table-column label="有效期" align="center" v-if="checked_obj.termOfValidityEnd">
        <template slot-scope="scope"> {{ G_time(scope.row.termOfValidityEnd, 0) }} </template>
      </el-table-column>

      <el-table-column label="合同是否上传" align="center" v-if="checked_obj.contractUrl">
        <template slot-scope="scope"> {{ scope.row.contractUrl ? '已上传' : '未上传' }} </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" v-if="checked_obj.createTime">
        <template slot-scope="scope"> {{ scope.row.createTime }} </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" v-if="checked_obj.createUser">
        <template slot-scope="scope"> {{ scope.row.createUser.realName }} </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="table_form.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="10"
      layout="prev, pager, next, jumper, sizes, total"
      :total="total_page"
      @size-change="handle_size"
      @current-change="handle_page">
    </el-pagination>

    <!-- 退课 -->
    <el-dialog
      title="退课"
      :visible.sync="is_drop_out"
      width="30%"
      center>
      <el-form ref="drop_out_form" :model="drop_out_form" label-width="100px">
        <el-form-item label="当前剩余课时：" prop="surplus">
          <el-input readonly type="number" v-model="drop_out_form.surplus">
            <template slot="append">节</template>
          </el-input>
        </el-form-item>

        <el-form-item label="退课节数：" prop="consumedClass">
          <el-input type="number" v-model="drop_out_form.consumedClass" @change="handle_class">
            <template slot="append">节</template>
          </el-input>
        </el-form-item>

        <el-form-item label="退课金额：" prop="orderPrice">
          <el-input readonly type="number" v-model="drop_out_form.orderPrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="备注：" prop="mark">
          <el-input type="textarea" v-model="drop_out_form.mark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="drop_out_close">返 回</el-button>
        <el-button type="primary" @click="drop_out_save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <EditPrivateOrder :status.sync="status" :row="row" :title="title" />
  </div>
</template>

<script>
  import { selectByRule, selectCoachByRule } from '@/utils/apiStore.js'
  import {  courseOptionValue, pay_selectByRule, selectCourseOrder, selectByMenuUrl, order_deleteByPrimaryKey, orderRefund }  from '@/utils/apiMember.js'
  import EditPrivateOrder from '@/components/editPrivateOrder.vue'
  export default {
    components: { EditPrivateOrder },
    data() {
      return {
        id: '', // 上一个页面传递过来的id
        table_form: {
          courseId: '', // 姓名
          buyCourseStoreId: '', // 门店
          saleUserId: '', // 教练
          orderNumber: '', // 订单号
          additionalOrder: '', // 是否补录
          tariffManagementId: '', // 付款方式
          endTime: '', // 创建时间
          createTimeBigin2: '', // 开始时间
          createTimeEnd2: '', // 结束时间
          page:               1,      // 页数
          rows:               10,     // 每页显示条数
        },
        total_page:           0,      // 总条数
        btn_data:             [],     // 表格顶部的操作按钮
        course_data: [], // 课程下拉框筛选数据
        store_data: [], // 门店下拉框筛选数据
        coach_data: [], // 教练下拉框筛选数据
        pay_data: [], // 付款方式下拉框筛选数据
        tableData: [], // 表格数据
        select_table_list: [], // 表格选中存储字段
        checked_obj: {
          orderNumber: true,
          autoStatus: true,
          storeName: true,
          realName: true,
          vipuser: true,
          phone: true,
          courseManagement: true,
          introduction: true,
          purchaseQuantity: true,
          unitPrice: true,
          earnestMoney: true,
          earnestMoney_price: true,
          tariffManagement: true,
          termOfValidityEnd: true,
          contractUrl: true,
          createTime: true,
          createUser: true
        },
        is_drop_out: false, // 退课蒙层
        drop_out_form: {
          surplus: 0, 
          consumedClass: '', 
          orderPrice: 0, 
          mark: '', 
          id: ''
        }, // 退课蒙层表单数据
        status: false, // 编辑私教订单组件显示隐藏
        row: '', // 编辑私教订单所选表格行数据
        title: '编辑私教订单', // 编辑私教订单 title
      }
    },
    mounted () {
      this.id = this.$route.query.id
      this.get_course()
    },
    methods: {
      // 搜索
      handle_search() {
        // 处理参数 时间
        if (this.table_form.endTime.length == 2) {
          this.table_form.createTimeBigin2  = this.table_form.endTime[0]
          this.table_form.createTimeEnd2    = this.table_form.endTime[1]
        } else {
          this.table_form.endTime           = ''
          this.table_form.createTimeBigin2  = ''
          this.table_form.createTimeEnd2    = ''
        }

        // 分页重置
        this.table_form.page                = 1
        this.table_form.rows                = 10

        this.set_table(this.table_form)
      },

      // 重置resetFields
      handle_reset() {
        this.$refs['table_form'].resetFields()
        this.table_form.page                = 1
        this.table_form.rows                = 10
        this.table_form.createTimeBigin2    = ''
          this.table_form.createTimeEnd2    = ''

        this.set_table(this.table_form)
      },

      // 获取课程
      get_course() {
        this.course_data = []
        courseOptionValue().then(res => {
          if (res.errCode == 200) {
            this.course_data = res.data

            this.get_store()
          }
        })
      },

      // 获取门店下拉框数据
      get_store() {
        this.store_data = []
        selectByRule({page: 1, rows: 999999}).then(res => {
          if (res.errCode == 200) {
            this.store_data = res.data.elements

            this.get_pay_type()
          }
        })
      },

      // 选择门店下拉框change事件 选择旗下的教练
      handle_store(val) {
        this.table_form.saleUserId    = ''
        this.coach_data               = []
        selectCoachByRule({ enterpriseStoreId: val, rows: 99999 }).then(res => {
          if (res.errCode == 200) {
            this.coach_data = res.data.elements
          }
        })
      },

      // 付款方式下拉框数据获取
      get_pay_type() {
        pay_selectByRule({ page: 1, rows: 99999}).then(res => {
          if (res.errCode == 200) {
            this.pay_data = res.data.elements

            this.set_table(this.table_form)
          }
        })
      },

      // 表格选中
      handle_select(value) {
        this.select_table_list = value
      },

      // 渲染表格方法
      set_table(params) {
        let _params           = JSON.parse(JSON.stringify(params))
        _params.id            = this.$route.query.id
        _params.endTime       = ''
        this.tableData        = []
        this.btn_data         = []
        selectCourseOrder(_params).then(res => {
          if (res.errCode == 200) {
            this.tableData    = res.data.elements
            this.total_page   = res.data.totalCount

            // 获取表格操作按钮
            selectByMenuUrl({ menuUrl: this.$route.path }).then(result => {
              if (result.errCode == 200) {
                this.btn_data = result.data
              }
            })
          }
        })
      },

      // 分页条数修改
      handle_size(rows) {
        this.table_form.rows = rows

        this.set_table(this.table_form)
      },

      // 页码数改变
      handle_page(page) {
        this.table_form.page = page

        this.set_table(this.table_form)
      },

      // 表格顶部按钮操作
      handle_table_btn(event_name) {
        if (this.select_table_list.length > 1) {
          return this.$message.error({
            message: '不能同时操作两条数据！',
            offset: document.body.offsetHeight / 2
          })
        }

        if (this.select_table_list.length == 0) {
          return this.$message.error({
            message: '请选择一条数据进行操作！',
            offset: document.body.offsetHeight / 2
          })
        }

        let id = this.select_table_list[0].id, row = this.select_table_list[0]
        switch (event_name) {
          //  编辑
          case 'edit': {
            this.status = true
            this.row    = row
            break
          }
          // 详情
          case 'detail': {
            break
          }
          // 删除
          case 'delete': {
            this.$confirm('确定删除?', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              order_deleteByPrimaryKey({id}).then(res => {
                if (res.errCode == 200) {
                  this.$message.success({
                    message: '删除成功！',
                    offset: document.body.offsetHeight / 2,
                    onClose: () => {
                      this.set_table(this.table_form)
                    }
                  })
                }
              })
            }).catch(action => {});
            break
          }
          // 退课
          case 'drop_out': {
            this.is_drop_out            = true
            this.drop_out_form.surplus  = row.remainingQuantity
            this.drop_out_form.id       = id
            break
          }
        }
      },

      // 导出excell
      handle_excell() {
         this.$confirm('是否导出excell表格?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
             this.G_excell2()
          }).catch(action => {});
      },

      /**
       * 处理表格中订单状态
       * 1：已退课          灰色
       * 2：即将过期        红色
       * 3：已过期          灰色
       * 4：已过期/不正常订单 灰色
       * 5：已完课          橙色
       * 6：正常            蓝色
       * */ 
      set_order_type(row) {
        if (row.isRefund == 1) {
          return 1
        } else {
          var nowDate = new Date();
          if(row.termOfValidityEnd !=null && row.remainingQuantity > 0){
            if((row.termOfValidityEnd - nowDate.getTime()) < 1000 * 60 * 60 * 24 *15 && (row.termOfValidityEnd - nowDate.getTime()) > 0){
              return 2
            }else if((row.termOfValidityEnd - nowDate.getTime()) < 0){
              return 3
            }
          }else if(row.termOfValidityEnd == null){
            return 4
          }else if(row.remainingQuantity == 0){
            return 5
          }
          return 6
        }
      },

      // 退课蒙层返回
      drop_out_close() {
        this.$refs['drop_out_form'].resetFields()
        this.drop_out_form.id = ''
        this.is_drop_out = false
      },

      // 退课蒙层确定
      drop_out_save() {
        console.log('this:', this.drop_out_form);
        orderRefund(this.drop_out_form).then(res => {
          if (res.errCode == 200) {
            this.$message.success({
              message: '退课成功！',
              offset: document.body.offsetHeight / 2,
              onClose: () => {
                this.drop_out_close()
                this.set_table(this.table_form)
              }
            })
          }
        })
      },

      // 退课蒙层退课节数change事件
      handle_class(val) {
        // 单价
        let unitPrice = this.select_table_list[0].unitPrice
        if (val > this.drop_out_form.surplus) {
          return this.$message.error({
            message: '退课节数不能大于当前剩余课时数！',
            offset: document.body.offsetHeight / 2,
            onClose: () => {
              this.drop_out_form.consumedClass = ''
              this.drop_out_form.orderPrice    = 0
            }
          })
        }
        this.drop_out_form.orderPrice = unitPrice * this.drop_out_form.consumedClass
      }
    },
  }
</script>

<style lang="scss" scoped>

</style>